package com.qk.exception;

import com.qk.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("服务器异常: {}", e.getMessage());
        return Result.error("请联系系统管理员，稍后重试");
    }

    @ExceptionHandler
    public Result DuplicateKeyException(DuplicateKeyException e){
        String errorMsg = e.getMessage();
        if (errorMsg.contains("Duplicate entry")){
            String msg = errorMsg.substring(errorMsg.indexOf("Duplicate entry"));
            String[] s = msg.split(" ");
            return Result.error(s[2] + " 已存在");
        }
        return Result.error("服务器异常，请稍后重试");
    }

    @ExceptionHandler
    public Result handleBusinessException(BusinessException e) {
        log.error("服务器异常: {}", e.getMessage());
        return Result.error(e.getMessage());
    }
}
